package univer.oko.gui.table;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class SortableTableModel extends DefaultTableModel {
  JTable table;
  JTableHeader header;
  Vector columnNames;
  int selectedHeaderColumn;
  int columnCount;
  int[] minWidth;
  TableCellRenderer[] cellRenderer;
  int clickCount = 0;

  public SortableTableModel( JTable table, String[] columnNames, int rowCount ){
    super( columnNames, rowCount );
    this.table = table;
      
    header.addMouseListener( new TableChangedAdapter() );
    this.columnNames = DefaultTableModel.convertToVector( columnNames );
    columnCount = columnNames.length;
    minWidth = new int[ columnCount ];
    cellRenderer = new TableCellRenderer[ columnCount ];
  }

  class TableChangedAdapter extends MouseAdapter {
    public void mousePressed( MouseEvent e ){
      Point mousePoint = new Point( e.getX(), e.getY() );
      selectedHeaderColumn = header.columnAtPoint( mousePoint );
      DefaultTableColumnModel cmodel = (DefaultTableColumnModel)table.getColumnModel();
      backupTableColumnAttr( cmodel );

      clickCount++;
      boolean reverseOrder = false;
      if( ( clickCount %2 )==0 ) reverseOrder = true;
      sort( reverseOrder );

      restoreTableColumnAttr( cmodel );
    }
    void backupTableColumnAttr( DefaultTableColumnModel cmodel ){
      for( int i=0 ; i< columnCount ; i++ ){
        TableColumn column = cmodel.getColumn(i);
        minWidth[i] = column.getMinWidth();
        cellRenderer[i] = column.getCellRenderer();
      }
    }
    void restoreTableColumnAttr( DefaultTableColumnModel cmodel ){
      for( int i=0 ; i< columnCount ; i++ ){
        TableColumn column = cmodel.getColumn(i);
        column.setMinWidth( minWidth[i] );
        column.setCellRenderer( cellRenderer[i] );
      }
    }
  }

  void sort( boolean reverseOrder ){
    Vector vec = getDataVector();
    Object[] array = vec.toArray();
    Arrays.sort( array, new Compare( selectedHeaderColumn, reverseOrder ) );
    vec = DefaultTableModel.convertToVector( array );
    setDataVector( vec, columnNames );
  }

  class Compare implements Comparator {
    int sortKey;
    boolean reverseOrder;
    Compare( int sortKey, boolean reverseOrder ){
      this.sortKey = sortKey;
      this.reverseOrder = reverseOrder;
    }
    public int compare( Object o1, Object o2 ){
      Vector v1 = (Vector)o1;
      Vector v2 = (Vector)o2;
      Comparable s1 = (Comparable)v1.get( sortKey );
      Comparable s2 = (Comparable)v2.get( sortKey );
      int ans = s1.compareTo( s2 );
      if( reverseOrder ) ans *= -1;
      return( ans );
    }
    public boolean equals( Object obj ){
      return( false );
    }

  }
}

